# _*_ coding: utf-8 _*_

import argparse
import json
import os


# from https://www.cnblogs.com/chenyansu/p/8300296.html
#   sort
def str_num_sort(strs):
    if str:
        try:
            filepath, filefullname = os.path.split(strs)
            filename, fileextname = os.path.splitext(filefullname)
            num = int(filename)
            return num
        except:
            return -1
    else:
        return -99


def test(directory):
    directory = os.path.abspath(directory)
    walk = os.walk(directory)
    dirname = os.path.dirname(directory)
    basename = os.path.basename(directory)
    print(dirname, basename)
    video_map = {}
    video_save_path = ''
    for root, dirs, files in walk:
        for file in sorted(files, key=str_num_sort):
            if file == 'entry.json':
                json_file_name = os.path.join(root, file)
                with open(json_file_name) as json_file:
                    video_info = json.loads(json_file.read())
                    video_title = video_info['title']
                    video_name = video_info['page_data']['part'].replace(' ', '_')

                    # mkdir to save video
                    video_save_path = os.path.join(dirname, basename + "-" + video_title)
                    if not os.path.isdir(video_save_path):
                        os.mkdir(video_save_path)
                    root_basename = os.path.basename(root)

                    # save video name map
                    video_map[root_basename] = video_name

            if file.endswith('.blv'):
                part_video_slice_path = os.path.join(root, file)
                part_basename = os.path.dirname(root)
                part_path, part_name = os.path.split(part_basename)
                part_video_slice_list_file = os.path.join(part_path, part_name+".txt")
                with open(part_video_slice_list_file, "a+") as slice_list_file:
                    slice_list_file.writelines("file '" + part_video_slice_path + "'\n")

    print(video_map)
    for part in video_map:
        part_video_slice_list_file = os.path.join(directory, part + ".txt")
        part_video_path_name = os.path.join(video_save_path, part + '_' + video_map[part] + ".mp4")
        cmd = "ffmpeg -f concat -safe 0 -i {}  -c copy {}".format(part_video_slice_list_file, part_video_path_name)
        print(cmd)
        os.system(cmd)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d',
                        '--directory',
                        help='bilibili video directory, default current directory',
                        type=str,
                        default="./")
    args = parser.parse_args()
    test(args.directory)
    # with open(argv[1]) as json_file:
    #     json_string = json_file.read()
    #     json_obj = json.loads(json_string)
    #     video_name = json_obj['page_data']['part']
    #     video_name = video_name.replace(" ", "_")
    #     print(video_name)


if __name__ == '__main__':
    main()
